<?php
/**
 * 处理用户手打牌类
        * Class PM_c
 */
class PM_c
{
    public static function __index( $room_id , $put_uid , $card_number , $db_connect ){
        //取出房间信息
        $room_info  = $db_connect->select('*')->from('tt_room')->where("room_id= '". $room_id ."' ")->row();
        //取出该房间对应的所有当前局的玩家的手牌相关的card信息 - 应该是4条记录
        $card_info  = $db_connect->select('*')->from('tt_room_card')->where("jid = '". $room_info['room_js'] ."' and rid= '". $room_id ."' ")->orderByASC( array('id') )->query();
        $card_info  = PHZ_Card::__cardInfoUserSort( $card_info , $put_uid );//按照出牌人的顺序进行整理
        //去除用户手牌并同时增加一个下牌
        PHZ_Card::__delete_user_SP_AND_Add_BP( $card_info  ,  $put_uid , $card_number , $db_connect );
        //添加一个put_log记录
        PHZ_Card::__InsertPut_LogCard( $room_info ,  $put_uid , $card_number , $db_connect );
        //设置当前房间出牌人以及牌号 - 设置
        PHZ_Room::__setThisPutCard( $room_id , $put_uid , $card_number , false , $db_connect );
        //用户手打牌；直接添加该用户的pass_吃跟pass_碰记录
        PHZ_Card::__set_UserInputPai_PassLOG( $room_info , $put_uid , $card_number , $db_connect );
        //send-to-all：某位玩家出牌信息
        $temp = array();
        $temp['pl']          = 2;//2为普通出牌-即所有人可见的打掉牌
        $temp['card_number'] = $card_number;//牌号
        $temp['put_uid']     = 0;$temp['mop_uid'] = 0;//摸牌&出牌权
        $temp['is_op']       = PM_c_aux::__queryHandPut_ISoperation( $room_info , $card_info ,$put_uid , $card_number , $db_connect );//是否存在操作？--2017.12.11
        PHZ_Log::__send_user_log( $room_info , $put_uid , $temp , $db_connect );
        //设置出牌权
        PHZ_Room::__setThisPutUser( $room_info['room_id'] , $temp['put_uid'] , $db_connect );
        //第一次进行平胡-判胡操作（因为有的玩家可能不需要跑；但可以用跑的那个字来胡牌；所以这里必须打出来的第一时间就判断是否能胡牌）
        $pinghu_uid = PHZ_CanHu::__chkAllUser_returnHU_UID( $room_id , $put_uid , $card_number , $db_connect );
        if( $pinghu_uid > 0 ){
            //是否还有人能跑这个牌，如果有跑的，则 - （PS:跑的这个人不能跟平胡是同一个人，如果能跑的人平胡是同一个人，那么就允许胡的；破跑胡）
            $is_can_pao_uid = self::__is_can_pao( $card_info , $card_number );
            if( $is_can_pao_uid > 0 && $is_can_pao_uid != $pinghu_uid ){
                //.....
            }else{
                $canhu = PHZ_CanHu::__chkAllUser_canHu( $room_id , $put_uid , 'hand' , $card_number , $db_connect , false , 0);
                if( $canhu == true ) {
                    PM_m::__index();
                    return true;
                }
            }
        }
        //判断当前是否有玩家满足该牌的跑牌（即手中有3个相同的）
        $is_pao = self::__is_pao( $room_info , $card_info , $put_uid , $card_number , $db_connect );
        //判断当前是否有玩家满足该牌的下跑（即各用户已经畏了的牌） - 能跑就不会有下跑
        if( $is_pao['status'] == false ) {
            $is_xia_pao = self::__is_xiapao( $room_info , $card_info , $put_uid ,  $card_number , $db_connect );
        }
        //跑牌判断结束后；判断是否有玩家能胡牌？(注意当前要代入是否有跑牌)
        if( $is_pao['status'] == true ){
            $is_hu = PHZ_CanHu::__chkAllUser_canHu( $room_id , $put_uid , 'hand' , $card_number , $db_connect , true , $is_pao['uid'] );
        }else if( $is_xia_pao['status'] == true ){
            $is_hu = PHZ_CanHu::__chkAllUser_canHu( $room_id , $put_uid , 'hand' , $card_number , $db_connect , true , $is_xia_pao['uid'] );
        }else{
            $is_hu = PHZ_CanHu::__chkAllUser_canHu( $room_id , $put_uid , 'hand' , $card_number , $db_connect , false , 0);
        }
        //如果胡牌，则调用胡牌后的数据处理&房间处理
        if( $is_hu == true ){
            PM_m::__index();return true;
        }
        //如果没有人胡,则需要对刚刚的跑牌做处理（重跑则自动下摸；普通跑则不管）
        if( $is_pao['status'] == true ) {
            if( $is_pao['is_chongpao'] == 1 ){
                PM_n::__index( $room_info , $is_pao['uid'] , 0 , $db_connect );
            }
            return true;
        }
        if( $is_xia_pao['status'] == true ) {
            if( $is_xia_pao['is_chongpao'] == 1 ){
                PM_n::__index( $room_info , $is_xia_pao['uid'] , 0 , $db_connect );
            }
            return true;
        }
        //判断是否有人能碰牌？ - 碰牌建立在没有过章的情况下
        $is_peng  = false;$peng_uid = 0;
        foreach ($card_info as $key => $value) {
            if ($value['uid'] != $put_uid) {
                $find = 0;
                $temp = explode(",", $value['sp']);
                foreach ($temp as $k1 => $v1) {if ($card_number == $v1) {$find++;}}//解析手牌；找碰牌
                if( $find == 2 ){
                    //当前碰牌者的手牌数量剩余判断-2张不允许碰
                    $lastChk = true;if( PHZ_Card::__chkCHiPeng_Last( $value['sp'] ) == false ){$lastChk = false;}
                    //即使找到了碰牌者，碰牌人是否过章？
                    if( $lastChk == true && PHZ_User::__Peng_card_is_Out( $room_info , $value['uid'] , $card_number , $db_connect ) == true ) {
                        $is_peng = true;
                        $peng_uid = $value['uid'];//设置碰牌者信息
                        $temp = array();
                        $temp['pl'] = 3;//3为碰牌，碰牌只可能是自己看到，所以前端只需要处理自身即可
                        $temp['card_number'] = $card_number;//牌号
                        $temp['put_uid'] = 0;//全部人丧失出牌权
                        $temp['mop_uid'] = 0;//全部人丧失摸牌权
                        $temp['is_peng'] = 1;//当前是有碰
                        $temp['peng_uid'] = $peng_uid;//允许碰的人的用户ID
                        PHZ_Log::__send_user_log_IN_Single($room_info, $put_uid, $peng_uid, $temp, $db_connect);//给单人发送信息
                        //获取当前碰的人的索引
                        $peng_index = PHZ_Tools::__get_user_in_room_index( $room_info , $value['uid'] );
                        $db_connect->update('tt_room')->cols(array('p' . $peng_index . '_is_peng' => 1))->where('room_id=' . $room_id)->query();//更新当前碰状态
                    }
                    break;//碰牌只会有一个，找到则结束
                }
            }
        }
        //设置出牌权
        PHZ_Room::__setThisPutUser( $room_info['room_id'] , 0 , $db_connect );
        //判断是否有人能吃牌 - 吃牌建立在自己没有过章的情况下(注意；手打牌，吃牌只能是下家)
        $is_chi   = false;
        $next_uid = PHZ_User::__get_user_Next_userID( $room_info , $put_uid );//获取下家用户ID
        foreach ($card_info as $key => $value) {
            if ($value['uid'] == $next_uid) {
                $next_user_card_info = $value;break;//获取下家的牌面信息
            }
        }
        $next_index = PHZ_User::__get_user_Room_Index( $room_info , $next_uid );//获取下家的位置索引
        if( PHZ_User::__Eat_card_is_Out( $room_info , $next_uid , $card_number , $db_connect  ) == true ) {
            //当前碰牌者的手牌数量剩余判断-2张不允许吃
            $lastChk = true;if( PHZ_Card::__chkCHiPeng_Last( $value['sp'] ) == false ){$lastChk = false;}
            $chi_pai = PHZ_Chi_Bi_Pai::__chi_pai_bi_pai_chk( $card_number, $next_user_card_info['sp'] , $room_info );//查询吃牌&比牌信息
            if ($lastChk == true && $chi_pai != false && count($chi_pai) >= 1) {
                $is_chi = true;
                $temp = array();
                $temp['pl'] = 4;//4为吃牌，打牌情况下，吃只可能是下家一个人看到
                $temp['card_number'] = $card_number;//牌号
                $temp['put_uid']     = 0;//全部人丧失出牌权
                $temp['mop_uid']     = 0;//全部人丧失摸牌权
                $temp['chi_pai']     = $chi_pai;//可以吃的牌
                $temp['is_peng']     = $is_peng == false ? 0 : 1;//该牌是否有碰？
                $temp['peng_uid']    = $peng_uid;//可以碰的人的用户ID
                $temp['is_chi']      = 1;//是否有吃？
                $temp['chi_uid']     = $next_uid;//因为是手打牌，所以允许吃的人顶多也就是一个了
                PHZ_Log::__send_user_log_IN_Single( $room_info , $put_uid , $next_uid , $temp , $db_connect );//给单人发送信息
                //将下家的吃状态设置为1，方便后续的碰的人取消，吃还能继续执行
                $db_connect->update('tt_room')->cols(array('p' . ($next_index) . '_is_chi' => 1))->where('room_id=' . $room_id)->query();
            }
        }
        //设置出牌权
        PHZ_Room::__setThisPutUser( $room_info['room_id'] , 0 , $db_connect );
        //如果当前有吃或者有碰的情况下；则程序流退出；否则执行下家自动摸牌操作
        if( $is_peng == true || $is_chi == true ) {
            return false;
        }
        //所有流程执行结束；该牌没人要的进；执行下家自动摸牌
        PM_n::__index( $room_info , $put_uid , 0 , $db_connect , $put_uid , $card_number );
    }

    /**
     * 查询是否有用户能跑这个牌
     * @param $card_info
     * @param $card_number
     */
    public static function __is_can_pao( $card_info , $card_number ){
        foreach( $card_info as $key => $value ){
            $have_count = 0;//默认拥有0张
            $temp_sp = $value['sp'];$temp_sp = explode(",",$temp_sp);
            foreach( $temp_sp as $key_1 => $value_1 ){
                if( $value_1 == $card_number ){
                    $have_count++;
                }
            }
            $is_wei       = false;
            $mop_card_wei = explode(",", $value['card_wei'] );
            foreach ( $mop_card_wei as $key_1 => $value_1 ){if( $value_1 == $card_number ){ $is_wei = true; }}//该摸牌人是否畏过该牌
            if( $have_count >= 3 || $is_wei == true ){
                return $value['uid'];
            }
        }
        return 0;
    }

    /**
     * 玩家出牌后；检测其他玩家是否存在跑（手中）的牌的信息
     * @param $room_info 房间信息
     * @param $card_info 房间手牌信息
     * @param $put_uid 谁打的牌？
     * @param $card_number 打的什么
     * @param $db_connect
     */
    public static function __is_pao( $room_info , $card_info , $put_uid , $card_number , $db_connect){
        $card_is_pao       = 0;//是否有跑牌
        $card_is_chongpao  = 0;//是否有重跑
        $card_is_tipao_cnt = 0;//如果有人能跑，记录下他的ti_pao数
        $card_pao_id       = 0;//能跑的这个人的用户ID
        $card_pao_sys_id   = 0;//能跑的这个人的系统ID，（方便update）
        $card_pao_sys_xp   = "";//记录跑牌者的下牌信息
        $card_pao_sys_sp   = "";//记录跑牌者的手牌信息(方便update)
        foreach( $card_info as $key => $value ){
            if( $value['uid'] == $put_uid ){
                $put_user_card_info = $value;break;
            }
        }
        foreach( $card_info as $key => $value ){
            $have_count = 0;//默认拥有0张
            $temp_sp = $value['sp'];$temp_sp = explode(",",$temp_sp);
            foreach( $temp_sp as $key_1 => $value_1 ){
                if( $value_1 == $card_number ){
                    $have_count++;
                }
            }
            if( $have_count >= 3 ){//如果有人有3张的情况下，向全局用户发送log信息（并且break，正常情况下，一张同样的牌，顶多4张了，怎么可能还有另外的人能跑？）
                $card_is_pao       = 1;//有跑
                $card_pao_id       = $value['uid'];//谁跑？
                $card_is_tipao_cnt = $value['ti_pao'];//记录跑人的提跑数
                $card_pao_sys_id   = $value['id'];
                $card_pao_sys_xp   = $value['xp'];//记录跑牌人手里的下牌
                $card_pao_sys_sp   = $value['sp'];//记录跑牌人的手牌信息
                break;
            }
        }
        if( $card_is_pao == 1 ){//判断当前跑牌人是否满足重跑条件(::已经存在至少1跑了，那么这一跑，就算是重跑)
            //是否重跑
            if( $card_is_tipao_cnt >= 1 ){ $card_is_chongpao = 1;}
            //更新出牌者的bp信息（其实就是bp恢复）
            $db_connect->update('tt_room_card')->cols(array( 'bp' => $put_user_card_info['bp'] ))->where('id=' . $put_user_card_info['id'] )->query();
            //更新跑信息(在原有跑上面+1)& 下牌信息
            $card_pao_sys_xp = $card_pao_sys_xp . $card_number . "_" . $card_number . "_" . $card_number . "_" . $card_number . "," ;
            //设置当前房间出牌人以及牌号 - 清空
            PHZ_Room::__setThisPutCard( $room_info['room_id'] , 0 , 0 , true , $db_connect );
            //更新跑的人手牌信息（手牌里的对应牌全部去除）
            $card_pao_sys_sp = explode(",",$card_pao_sys_sp);
            foreach ($card_pao_sys_sp as $key => $value){
                if( $value == $card_number ){unset( $card_pao_sys_sp[$key] );}
            }
            $db_connect->update('tt_room_card')->cols(array('sp'=> implode(",",$card_pao_sys_sp) ,'xp'=> $card_pao_sys_xp ,'ti_pao'=> ($card_is_tipao_cnt+1)  ))->where('id=' . $card_pao_sys_id )->query();
        }
        if( $card_is_pao == 1 ){//增加跑牌者的息数
            PHZ_SuanXi::__xi( $room_info , $card_pao_id , "hand_pao" , $card_number , $db_connect );
        }
        if( $card_is_pao == 1 ){//给所有人发送跑牌信息
            $temp = array();
            $temp['pl']          = 11;//11为玩家打出了一张牌，该牌恰好可以被某个人手里的牌起跑
            $temp['card_number'] = $card_number;//牌号
            if( $card_is_chongpao == 1 ){
                $temp['put_uid'] = 0;//重跑：所有人失去出牌权
            }else{
                $temp['put_uid'] = $card_pao_id;//首跑：出牌权为自身
            }
            $temp['mop_uid']     = 0;//跑牌人
            $temp['who_pao']     = $card_pao_id;//跑牌人
            $temp['is_chong']    = $card_is_chongpao;//是否重跑
            PHZ_Log::__send_user_log( $room_info , $put_uid , $temp , $db_connect );
            //设置出牌权
            PHZ_Room::__setThisPutUser( $room_info['room_id'] , $temp['put_uid'] , $db_connect );
        }
        if( $card_is_pao == 0 ){
            return array('status'=>false , 'uid' => 0);
        }else{
            return array('status' => true , 'uid' => $card_pao_id , 'is_chongpao' => $card_is_chongpao );
        }
    }


    public static function __is_xiapao( $room_info , $card_info , $put_uid ,  $card_number , $db_connect ){
        //下跑的牌，畏的的时候组合是什么样子？
        $xia_pao_string    = $card_number . "_" . $card_number . "_" . $card_number;
        $card_is_chongpao  = 0;//是否有重跑
        $card_is_tipao_cnt = 0;//如果有人能跑，记录下他的ti_pao数
        $card_pao_id       = 0;//能跑的这个人的用户ID
        $card_pao_sys_id   = 0;//能跑的这个人的系统ID，（方便update）
        $card_pao_sys_xp   = "";//记录跑牌者的下牌信息
        //遍历所有人的下牌信息，看是否有人能成功支持畏牌的下跑
        $card_is_xia_pao = 0;
        foreach( $card_info as $key => $value ){
            //必须是畏的牌，才存在手打牌“下跑”
            $card_is_wei = false;
            //切割每个人的畏过的牌的记录；如果能找到匹配当前打出的牌的话；才能进行查找畏牌记录
            $temp_card_wei = $value['card_wei'];$temp_card_wei = explode(",",$temp_card_wei);
            foreach ( $temp_card_wei as $key_2 => $value_2 ){
                if( $value_2 == $card_number ){
                    $card_is_wei = true;break;
                }
            }
            if( $card_is_wei == true ){
                $temp_sp = $value['xp'];$temp_sp = explode(",",$temp_sp);
                foreach( $temp_sp as $key_1 => $value_1 ){
                    if( $value_1 != "" && $value_1 == $xia_pao_string ){
                        $card_is_xia_pao   = 1;//下跑肯定只有1次，找到了就退出就好了，不用再次执行
                        $card_pao_id       = $value['uid'];//谁跑？
                        $card_is_tipao_cnt = $value['ti_pao'];//记录跑人的提跑数
                        $card_pao_sys_id   = $value['id'];//跑牌人的牌记录系统ID
                        $card_pao_sys_xp   = $value['xp'];//记录跑牌人手里的下牌
                        break;
                    }
                }
            }
        }
        /**************************************  找到下跑了？能下跑？ ****************************************************/
        //1.自身将畏牌，变成跑牌；ti_pao的数量 + 1 ； xp中；新增一个号码记录
        if( $card_is_xia_pao == 1 ){
            //畏牌变跑牌，替换下牌
            $card_pao_sys_xp   = str_replace( $xia_pao_string , $xia_pao_string."_".$card_number  , $card_pao_sys_xp );
            //更新下跑者手中的xp信息(下牌，提跑数)
            $db_connect->update('tt_room_card')->cols(array('xp'=> $card_pao_sys_xp ,'ti_pao'=> ($card_is_tipao_cnt+1)  ))->where('id=' . $card_pao_sys_id )->query();
            //设置当前房间出牌人以及牌号 - 清空
            PHZ_Room::__setThisPutCard( $room_info['room_id'] , 0 , 0 , true , $db_connect );
            //出牌者手中的BP数 需要找到并减掉当前这个被下跑的牌
            foreach( $card_info as $key => $value ){
                if( $value['uid'] == $put_uid ){
                    $bp = explode(",", $value['bp'] );
                    foreach ( $bp as $key_1 => $value_1 ){
                        if( $value_1 == $card_number ){
                            unset( $bp[$key_1] );break;//只能删除1个
                        }
                    }
                    //执行删除query
                    $db_connect->update('tt_room_card')->cols(array( 'bp' => implode(",",$bp) ))->where('id=' . $value['id'] )->query();
                }
            }
        }
        if( $card_is_xia_pao == 1 ) {//增加息数
            PHZ_SuanXi::__xi( $room_info , $card_pao_id , "hand_xiapao" , $card_number , $db_connect );
        }
        if( $card_is_xia_pao == 1 ) {
            //本次下跑是否为重跑？;如果系统已经存在1次提跑了，那么本次跑牌则为重跑；
            if ($card_is_tipao_cnt >= 1) {
                $card_is_chongpao = 1;
            }
            //给全局所有人广播一个下跑信息；
            $temp = array();
            $temp['pl'] = 14;//14为玩家打出了一张牌，该牌恰好对应另一个玩家已经畏过的牌；；称为”下跑“
            $temp['card_number'] = $card_number;//牌号
            $temp['put_uid']  = $card_is_chongpao == 1 ? 0 : $card_pao_id;//牌牌人为重跑情况下，失去出牌权
            $temp['mop_uid']  = 0;//跑牌人
            $temp['who_pao']  = $card_pao_id;//跑牌人
            $temp['is_chong'] = $card_is_chongpao;//是否重跑
            PHZ_Log::__send_user_log($room_info, $put_uid, $temp, $db_connect);
            //设置出牌权
            PHZ_Room::__setThisPutUser( $room_info['room_id'] , $temp['put_uid'] , $db_connect );
        }
        if( $card_is_xia_pao == 0 ){
            return array('status'=>false , 'uid' => 0);
        }else{
            return array('status' => true , 'uid' => $card_pao_id , 'is_chongpao' => $card_is_chongpao );
        }
    }

}